package com.emsite.auth.util;

import com.emsite.common.constant.CommonConstant;
import com.emsite.common.constant.SecurityConstants;
import com.emsite.common.vo.SysRole;
import com.emsite.common.vo.UserVO;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* @Description: 重写Security的用户认证信息工具类
* @author lix
* @date 2018/8/20 15:01
*/
@Data
public class UserDetailsImpl implements UserDetails {
    private static final long serialVersionUID = 1L;
    private Integer userId;
    private String username;
    private String password;
    private String status;
    private Date accountExpired;
    private Date passwordExpired;
    private List<SysRole> roleList;

    public UserDetailsImpl(UserVO userVo) {
        this.userId = userVo.getUserId();
        this.username = userVo.getUsername();
        this.password = userVo.getPassword();
        this.status = userVo.getStatus();
        this.accountExpired = userVo.getAccountExpired();
        this.passwordExpired = userVo.getPasswordExpired();
        roleList = userVo.getRoleList();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(roleList)){
            for (SysRole role : roleList) {
                authorityList.add(new SimpleGrantedAuthority(role.getRoleCode()));
            }
        }
        authorityList.add(new SimpleGrantedAuthority(SecurityConstants.BASE_ROLE));
        return authorityList;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        if(null != this.accountExpired && this.accountExpired.compareTo(new Date()) < 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return StringUtils.equals(CommonConstant.STATUS_LOCK, status) ? false : true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        if(null != this.passwordExpired && this.passwordExpired.compareTo(new Date()) < 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean isEnabled() {
        return StringUtils.equals(CommonConstant.STATUS_DEL, status) ? false : true;
    }
}

